package xyz.ibenben.zhongdian.common.intercepter;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.entity.InnerMail;
import xyz.ibenben.zhongdian.system.entity.sys.*;
import xyz.ibenben.zhongdian.system.service.InnerMailService;
import xyz.ibenben.zhongdian.system.service.sys.*;

import javax.servlet.ServletContext;
import javax.servlet.http.*;
import java.util.List;

/**
 * 自定义拦截器
 *
 * @author  chenjian
 * @since	2016年1月7日
 */
public class MyInterceptor extends HandlerInterceptorAdapter {
	private SysResourcesService resourcesService;
	private SysUserService sysUserService;
	private InnerMailService innerMailService;

	/**
	 * 之前拦截
	 * @param request 参数
	 * @param response 参数
	 * @param handler 参数
	 * @return 返回值
	 * @throws Exception 异常
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//System.out.println(">>>MyInterceptor>>>>>>>在请求处理之前进行调用（Controller方法调用之前）" + request.getRequestURL())
		// 只有返回true才会继续向下执行，返回false取消当前请求
		return true;
	}

	/**
	 * 之后拦截
	 * @param request 参数
	 * @param response 参数
	 * @param handler 参数
	 * @param modelAndView 参数
	 * @throws Exception 异常
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		processService(request);
		processUri(request, modelAndView);
		processInnerMail(request);

	}

	/**
	 * 处理URI
	 * @param request 参数
	 * @param modelAndView 参数
	 */
	private void processUri(HttpServletRequest request, ModelAndView modelAndView) {
		//System.out.println(">>>MyInterceptor>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）")
		String uri = request.getRequestURI();
		if(null == modelAndView || resourcesService == null){
			return;
		}
		if(uri.contains("/upload")){
			modelAndView.getModelMap().addAttribute("nav", "上传图像");
		}
		//拦截目录下请求，是否为ajax请求
		if (null != request.getHeader("x-requested-with") && "XMLHttpRequest".equalsIgnoreCase(request.getHeader("x-requested-with"))){
			//ajax请求
		}else{
			SysResources sr = resourcesService.findNameByResurl(uri);
			if(null != sr){
				modelAndView.getModelMap().addAttribute("nav", sr.getName());
			}else{
				modelAndView.getModelMap().addAttribute("nav", "");
			}
		}
	}

	/**
	 * 处理服务
	 * @param request 参数
	 */
	private void processService(HttpServletRequest request) {
		ServletContext sc = request.getSession().getServletContext();
		WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);
		String resourceService = "sysResourcesService";
		String userService = "sysUserService";
		String mailService = "innerMailService";
		if(cxt != null){
			if(cxt.getBean(resourceService) != null){
				resourcesService = (SysResourcesService) cxt.getBean(resourceService);
			}
			if(cxt.getBean(userService) != null){
				sysUserService = (SysUserService) cxt.getBean(userService);
			}
			if(cxt.getBean(mailService) != null){
				innerMailService = (InnerMailService) cxt.getBean(mailService);
			}
		}
	}

	/**
	 * 处理站内信
	 * @param request 参数
	 */
	private void processInnerMail(HttpServletRequest request){
		Long userId = (Long)request.getSession().getAttribute(Constants.SESSIONID);
		if(null != userId){
			SysUser user = sysUserService.selectByKey(userId);
			String type = "BackNotice";
			if(user.getType()){
				type = "FrontNotice";
			}
			List<InnerMail> list = innerMailService.findAllNoticeByUserId(userId, type);
			request.setAttribute("innerMailList", list);
			int count = innerMailService.findCountByUserId(userId);
			request.setAttribute("innerMailListCount", count);
		}
	}

	/**
	 * 结束拦截
	 * @param request 参数
	 * @param response 参数
	 * @param handler 参数
	 * @param ex 参数
	 * @throws Exception 异常
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//System.out.println(">>>MyInterceptor>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）")
	}

}
